package com.example.core.interceptor;

import com.example.core.context.CommonContext;
import com.example.core.context.CommonContextInit;
import com.example.core.context.CustomContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ContextHandlerInterceptor implements HandlerInterceptor {

    public ContextHandlerInterceptor() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String app = this.getApp(request);
        CustomContext customContext = new CustomContext(app);
        customContext.setDataSourceApp(app);
        CommonContextInit.init(customContext);
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        CommonContext.remove();
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        CommonContext.remove();
    }


    private String getApp(HttpServletRequest request) {
        String app = request.getHeader("app");
        return StringUtils.isEmpty(app) ? null : app;
    }
}
